var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
var uglify = require('gulp-uglify');
var cleanCSS = require('gulp-clean-css');
var browserSync = require('browser-sync');
var rev = require('gulp-rev');
var revCollector = require('gulp-rev-collector');
var gutil = require('gulp-util');
const babel = require('gulp-babel');

gulp.task('default',function(){
	console.log('gulp启动成功！！')
})
// 自动刷新
gulp.task('browserSync', function() {
  browserSync({
    server: {
      baseDir: 'app'
    },
  })
}) 
//追加版本号
gulp.task('revJs',function(){
  return gulp.src('app/js/*.js')
    .pipe(rev())
    .pipe(rev.manifest())
    .pipe(gulp.dest('dist/js'))
});
gulp.task('revCss',function(){
  return gulp.src('app/css/*.css')
    .pipe(rev())
    .pipe(rev.manifest())
    .pipe(gulp.dest('dist/css'))
});

// JS,css 压缩模块
gulp.task('js',function(){
    gulp.src('app/js/*.js')
    // .pipe(uglify({ mangle: { toplevel: true }}))
    // .pipe(uglify())
    // 转化成es5
    .pipe(babel())
    .pipe(uglify({
        compress: {
            drop_console: true,  // 过滤 console
            drop_debugger: true  // 过滤 debugger
        }
    }))
    .on('error', function (err) {
        gutil.log(gutil.colors.red('[Error]'), err.toString());
    })   
    .pipe(gulp.dest('dist/js'))
});
gulp.task('css', function(){
	  gulp.src('app/css/*css')
    .pipe(cleanCSS({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist/css'));
});

//Html替换css、js文件版本
gulp.task('revHtml', function () {
    return gulp.src(['dist/**/*.json', 'app/*.html'])
        .pipe(revCollector())
        .pipe(htmlmin({
          collapseWhitespace:true,//压缩HTML
          removeComment:true,//清除HTML注释
          minifyJS:true,
          minifyCSS:true
        }))
        .pipe(gulp.dest('dist'))
        .pipe(browserSync.reload({
          stream: true
        }))
});
gulp.task('revHtml-module', function () {
    return gulp.src(['dist/**/*.json', 'app/module/*.html'])
        .pipe(revCollector())
        .pipe(htmlmin({
          collapseWhitespace:true,//压缩HTML
          removeComment:true,//清除HTML注释
          minifyJS:true,
          minifyCSS:true
        }))
        .on('error', function (err) {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
        }) 
        .pipe(gulp.dest('dist/module'))
        .pipe(browserSync.reload({
          stream: true
        }))
});

// 监听文件
gulp.task('watch',['browserSync','js','css','revJs','revCss','revHtml','revHtml-module'],function(){
    gulp.watch('app/js/*.js',['revJs']);
    gulp.watch('app/js/*.js',['js']);
    gulp.watch('app/css/*.css',['revCss']);
    gulp.watch('app/css/*.css',['css']);
    gulp.watch('app/*.html',['revHtml']);
    gulp.watch('app/module/*.html',['revHtml-module']);
})